package com.winhxd.b2c.customer.api;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.constant.CustomerConstant;
import com.winhxd.b2c.common.context.CustomerUser;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.CustomerDistributorCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerInfoCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerTotalCondition;
import com.winhxd.b2c.common.domain.customer.condition.MiniProgramStoreSharePicCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserEnum;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.model.CustomerUserInfo;
import com.winhxd.b2c.common.domain.customer.vo.CustomerAdminInfoVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerUserInfoSimpleVO;
import com.winhxd.b2c.common.domain.order.condition.OrderUsersCondition;
import com.winhxd.b2c.common.domain.order.vo.OrderUsersLevelProfitVO;
import com.winhxd.b2c.common.domain.order.vo.OrderUsersProfitListVO;
import com.winhxd.b2c.common.domain.order.vo.OrderUsersProfitVO;
import com.winhxd.b2c.common.domain.system.login.condition.CustomerChangeMobileCondition;
import com.winhxd.b2c.common.domain.system.login.condition.CustomerUserInfoCondition;
import com.winhxd.b2c.common.domain.system.user.condition.CheckUserCondition;
import com.winhxd.b2c.common.domain.system.user.model.SysUser;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.feign.message.MessageServiceClient;
import com.winhxd.b2c.common.feign.order.OrderDataStatisticsServiceClient;
import com.winhxd.b2c.common.feign.system.UserServiceClient;
import com.winhxd.b2c.common.util.DateUtil;
import com.winhxd.b2c.common.util.GeneratePwd;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.service.*;
import com.winhxd.b2c.customer.util.ValidateCustomerUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author baishenghu
 * @date 2019年1月8日 上午9:44:11
 * @Description 微信小程序查询Controller
 * @version
 */
@Api(value = "CustomerUserInfo Controller", tags = "C-User")
@RestController
@RequestMapping(value = "/api-customer/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ApiCustomerController extends ValidateCustomerUser {
	private static final Logger logger = LoggerFactory.getLogger(ApiCustomerController.class);

	@Autowired
	private CustomerLoginService customerLoginService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private DistributorService distributorService;

	@Autowired
	private Cache cache;
	@Autowired
	MessageServiceClient messageServiceClient;

	@Autowired
    OrderDataStatisticsServiceClient orderDataStatisticsServiceClient;

	@Autowired
    GraphicsGenerateService graphicsGenerateService;

    @Autowired
    private Environment env;

    @Autowired
    DistributorChannelService channelService;

    @Autowired
    private UserServiceClient userServiceClient;

    @Autowired
    private CustomerServiceClient customerServiceClient;

    /**
     * @author baishenghu
     * @date 2018年8月8日 下午8:56:52
     * @Description 用户换绑手机号
     * @param customerChangeMobileCondition
     * @return
     */
    @ApiOperation(value = "C端—用户换绑手机号")
    @ApiResponses({ @ApiResponse(code = BusinessCode.CODE_OK, message = "成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
            @ApiResponse(code = BusinessCode.CODE_1019, message = "验证码错误"),
            @ApiResponse(code = BusinessCode.CODE_1007, message = "参数无效") })
    @RequestMapping(value = "customer/2090/v1/customerChangeMobile", method = RequestMethod.POST)
    public ResponseResult<CustomerUserInfoSimpleVO> customerChangeMobile(
            @RequestBody CustomerChangeMobileCondition customerChangeMobileCondition) {
        logger.info("{} - 用户换绑手机号, 参数：customerUserInfoCondition={}", "",
                JsonUtil.toJSONString(customerChangeMobileCondition));
        if (null == customerChangeMobileCondition) {
            throw new BusinessException(BusinessCode.CODE_1007);
        }
        ResponseResult<CustomerUserInfoSimpleVO> result = new ResponseResult<>();
        CustomerUserInfoSimpleVO vo ;
        CustomerUser user = validateCustomerUser();
        CustomerUserInfo customerUserInfo = customerLoginService.getCustomerUserInfoById(user.getCustomerId());
        validateCustomerUserInfo(customerUserInfo);
        if (!customerChangeMobileCondition.getVerificationCode().equals(cache.get(
                CacheName.CUSTOMER_USER_SEND_VERIFICATION_CODE + customerChangeMobileCondition.getCustomerMobile()))) {
            logger.info("{} - 用户验证码错误",customerChangeMobileCondition.getVerificationCode());
            throw new BusinessException(BusinessCode.CODE_1019);
        }
        logger.info("换绑定手机号：{}",JsonUtil.toJSONString(customerUserInfo));
        CustomerUserInfoCondition customerUserMobile = new CustomerUserInfoCondition();
        customerUserMobile.setCustomerMobile(customerChangeMobileCondition.getCustomerMobile());
        customerUserMobile.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
        CustomerUserInfo customerMobile = customerLoginService.getCustomerUserInfoByCondition(customerUserMobile);
        if (null != customerMobile && StringUtils.isEmpty(customerMobile.getOpenid()) && CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode().intValue() == customerMobile.getLevel().intValue() && CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode().intValue() == customerUserInfo.getLevel().intValue()) {
            memberPromotion(customerUserInfo,customerMobile,customerChangeMobileCondition.getCustomerMobile());
        } else {
            modifyMobileAndAccount(customerUserInfo, customerChangeMobileCondition);
        }
        vo = customerLoginService.getCustomerUserInfoSimpleVO(customerUserInfo);
        result.setData(vo);
        return result;
    }

    /**
     * 会员晋升一级分销商
     * @param customerUserInfo
     * @param customerMobile
     * @param mobile
     */
    private void memberPromotion(CustomerUserInfo customerUserInfo,CustomerUserInfo customerMobile,String mobile){
        logger.info("会员信息对比：{}--------{}", JsonUtil.toJSONString(customerUserInfo), JsonUtil.toJSONString(customerMobile));
        cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customerUserInfo.getToken());
        cache.del(CacheName.CUSTOMER_USER_INFO_TOKEN + customerMobile.getToken());
        CheckUserCondition condition = new CheckUserCondition();
        condition.setCustomerId(customerMobile.getId());
        customerUserInfo.setLevel(customerMobile.getLevel());
        customerUserInfo.setCustomerMobile(mobile);
        customerUserInfo.setChannelId(customerMobile.getChannelId());
        customerUserInfo.setNickName(customerMobile.getNickName());
        customerUserInfo.setParentId(-1L);
        customerUserInfo.setStoreStatus(customerMobile.getStoreStatus());
        customerUserInfo.setStoreName(customerMobile.getStoreName());
        customerUserInfo.setStoreExplain(customerMobile.getStoreExplain() == null ? "" : customerMobile.getStoreExplain());
        customerUserInfo.setShopLogo(customerMobile.getShopLogo() == null ? "" : customerMobile.getShopLogo());
        customerUserInfo.setToken(GeneratePwd.getRandomUUID());
        customerUserInfo.setUpdated(new Date());
        customerUserInfo.setUpdatedByName(customerUserInfo.getWechatName() == null ? customerMobile.getNickName() : customerUserInfo.getWechatName());
        customerUserInfo.setId(customerUserInfo.getId());
        customerUserInfo.setStoreOpenCodeUrl("");
        customerUserInfo.setCustomerStoreCodeUrl("");
        customerUserInfo.setBindTime(new Date());
        customerUserInfo.setBindStatus(CustomerConstant.BIND_STATUS_OK);
        customerLoginService.updateCustomerInfo(customerUserInfo);
        ResponseResult<SysUser> resultUser = userServiceClient.getSysUserByCondition(condition);
        if (resultUser.getCode() == 0) {
            SysUser sysUser = resultUser.getData();
            sysUser.setCustomerId(customerUserInfo.getId());
            sysUser.setUpdatedBy(customerUserInfo.getId());
            sysUser.setUpdatedByName(customerMobile.getNickName() == null ? customerUserInfo.getWechatName() : customerMobile.getNickName());
            userServiceClient.modifySysUser(sysUser);
        }
        customerLoginService.removeCustomerInfo(customerMobile.getId());
    }

    /**
     * 绑定手机号和换绑手机号
     * @param customerUserInfo
     * @param customerChangeMobileCondition
     */
    private void modifyMobileAndAccount( CustomerUserInfo customerUserInfo,CustomerChangeMobileCondition customerChangeMobileCondition){
        customerLoginService.checkMobileAndAccount(customerUserInfo.getId(),customerChangeMobileCondition.getCustomerMobile());
        customerUserInfo.setCustomerMobile(customerChangeMobileCondition.getCustomerMobile());
        customerUserInfo.setUpdated(new Date());
        customerUserInfo.setUpdatedByName(customerUserInfo.getWechatName()==null?customerUserInfo.getNickName():customerUserInfo.getWechatName());
        customerUserInfo.setId(customerUserInfo.getId());
        customerUserInfo.setBindStatus(CustomerConstant.BIND_STATUS_OK);
        if (CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode().intValue() != customerUserInfo.getLevel().intValue()) {
            distributorService.verfySysUserMobile(customerChangeMobileCondition.getCustomerMobile(),customerUserInfo.getId());
            customerService.updateSystemUser(customerUserInfo);
        }else{
            if(null!=customerChangeMobileCondition.getShareCustomerId()) {
                CustomerUserInfo userParent = customerLoginService.findCustomerUserByLevel();
                validateCustomerUserInfo(userParent);
                if(userParent.getId().equals(customerUserInfo.getParentId())) {
                    CustomerUserInfo customer = customerLoginService.getCustomerUserInfoById(customerChangeMobileCondition.getShareCustomerId());
                    validateCustomerUserInfo(customer);
                    if (CustomerUserLevelEnum.CUSTOMER_LEVEL_0.getCode().intValue() == customer.getLevel().intValue()) {
                        customer = customerLoginService.getCustomerUserInfoById(customer.getParentId());
                    }
                    String openId = customer.getOpenid();
                    customerUserInfo.setParentId(customer.getId());
                    customerUserInfo.setChannelId(customer.getChannelId());
                    customerUserInfo.setStoreOpenCodeUrl("");
                    customerUserInfo.setCustomerStoreCodeUrl("");
                    //保存会员原始关系
                    customerLoginService.bindOriginalRelation(customerChangeMobileCondition.getShareCustomerId(),openId,customerUserInfo);
                }
            }
        }
        customerLoginService.updateCustomerInfo(customerUserInfo);
    }


    /**
     * 查询当前用户下面的会员信息
     * @param condition
     * @return
     */
    @ApiOperation(value = "微信小程序查询当前用户下面的会员信息")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
            @ApiResponse(code = BusinessCode.CODE_1007, message = "参数无效")})
    @RequestMapping(value = "customer/2091/v1/findCustomerParentIdPage", method = RequestMethod.POST)
    public ResponseResult<PagedList<CustomerDistributorVO>> findCustomerParentIdPage(@RequestBody CustomerTotalCondition condition) {
        String logTitle = "=/api-customer/customer/2091/v1/findCustomerParentIdPage-C端小程序查询当前用户下面的会员信息接口=";
        logger.info("{} - 参数：findCustomerParentIdPage={}", logTitle, JsonUtil.toJSONString(condition));
        ResponseResult<PagedList<CustomerDistributorVO>> result = new ResponseResult<>();
        try {
            CustomerUser user = validateCustomerUser();
            CustomerDistributorCondition distributorCondition = new CustomerDistributorCondition();
            distributorCondition.setFirstParentId(user.getCustomerId());
            distributorCondition.setFlag(2L);
           //老客1  新客0 通过sql进行判断
            distributorCondition.setAccessType(condition.getType());
            distributorCondition.setBindTime(DateUtil.getEndDate(new Date(),-1));
            distributorCondition.setPageNo(condition.getPageNo());
            distributorCondition.setPageSize(condition.getPageSize());
            distributorCondition.setIsIntegral(1);
            PagedList<CustomerDistributorVO> customerList = distributorService.findDistributerListByCondition(distributorCondition);
            CustomerUserInfo customerUserInfo = customerLoginService.getCustomerUserInfoById(user.getCustomerId());
            if(!customerList.getData().isEmpty()) {
                List<Long> customerIdList = new ArrayList<>();
                customerList.getData().forEach(v -> { customerIdList.add(v.getCustomerId());});
                OrderUsersCondition orderUsersCondition = new OrderUsersCondition();
                orderUsersCondition.setCustomerIds(customerIdList);
                orderUsersCondition.setAgentId(customerServiceClient.getParentCustomerUserByCustoemrId(customerIdList.get(0)).getData().getId());
                ResponseResult<List<OrderUsersProfitListVO>> listResponseResult = orderDataStatisticsServiceClient.findOrderUsersProfitList(orderUsersCondition);
                if(CustomerConstant.DEFAULT_STATUS ==listResponseResult.getCode()){
                    customerList.getData().forEach(v -> {
                        listResponseResult.getData().forEach(o -> {
                            if(v.getCustomerId().equals(o.getCustomerId())) {
                                List<OrderUsersProfitVO> oldList = o.getList();
                                List<OrderUsersLevelProfitVO> newList = new ArrayList<>();
                                oldList.forEach(p ->{
                                    OrderUsersLevelProfitVO vo = new OrderUsersLevelProfitVO();
                                    BeanUtils.copyProperties(p,vo);
                                    if(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode().intValue()==customerUserInfo.getLevel().intValue()){
                                        vo.setAgentActualProfit(p.getFirstAgentActualProfit());
                                        vo.setAgentEstimateProfit(p.getFirstAgentEstimateProfit());
                                    }else if(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode().intValue()==customerUserInfo.getLevel().intValue()){
                                        vo.setAgentActualProfit(p.getTwoAgentActualProfit());
                                        vo.setAgentEstimateProfit(p.getTwoAgentEstimateProfit());
                                    }
                                    newList.add(vo);
                                });
                                v.setList(newList);
                            }
                        });
                    });
                }
            }
            result.setData(customerList);
        } catch (Exception e) {
            logger.error("findCustomerParentIdPage分页查询自己下面的会员失败：",e);
            result.setCode(BusinessCode.CODE_1001);
        }
       return result;
    }

    /**
     * 查询当前会员管理平台信息
     * @param condition
     * @return
     */
    @ApiOperation(value = "微信小程序查询当前会员管理平台信息")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
            @ApiResponse(code = BusinessCode.CODE_1007, message = "参数无效")})
    @RequestMapping(value = "customer/2092/v1/getCustomerAdminInfo", method = RequestMethod.POST)
    public ResponseResult<CustomerAdminInfoVO> getCustomerAdminInfo(@RequestBody CustomerInfoCondition condition) {
        String logTitle = "=/api-customer/customer/2092/v1/getCustomerAdminInfo-C端小程序查询当前会员管理平台信息接口=";
        logger.info("{} - 参数：getCustomerAdminInfo={}", logTitle, JsonUtil.toJSONString(condition));
        ResponseResult<CustomerAdminInfoVO> result = new ResponseResult<>();
        try {
            CustomerAdminInfoVO vo = new CustomerAdminInfoVO();
            CustomerUser user = validateCustomerUser();
            CustomerUserInfo customerUserInfo = customerLoginService.getCustomerUserInfoById(user.getCustomerId());
            validateCustomerUserInfo(customerUserInfo);
            String url = env.getProperty("admin.login.url");
            vo.setAccount(customerUserInfo.getCustomerMobile());
            vo.setAdminUrl(url);
            result.setData(vo);
        } catch (Exception e) {
            logger.error("getCustomerAdminInfo查询当前会员管理平台信息失败：",e);
            result.setCode(BusinessCode.CODE_1001);
        }
        return result;
    }
    /**
     * 查询当前会员管理平台信息
     * @param condition
     * @return
     */
    @ApiOperation(value = "微信小程序查询当前会员二维码信息")
    @ApiResponses({@ApiResponse(code = BusinessCode.CODE_OK, message = "成功"),
            @ApiResponse(code = BusinessCode.CODE_1001, message = "服务器内部异常"),
            @ApiResponse(code = BusinessCode.CODE_1007, message = "参数无效")})
    @RequestMapping(value = "customer/2093/v1/getCustomerStore", method = RequestMethod.POST)
    public ResponseResult<CustomerAdminInfoVO> getCustomerStore(@RequestBody CustomerUserInfoCondition condition) {
        String logTitle = "=/api-customer/customer/2093/v1/getCustomerStore-C端小程序查询当前会员二维码信息接口=";
        logger.info("{} - 参数：getCustomerStore={}", logTitle, JsonUtil.toJSONString(condition));
        ResponseResult<CustomerAdminInfoVO> result = new ResponseResult<>();
        try {
            CustomerAdminInfoVO vo = new CustomerAdminInfoVO();
            CustomerUser user = validateCustomerUser();
            String path="";
            CustomerUserInfo customerUserInfo = customerLoginService.getCustomerUserInfoById(user.getCustomerId());
            validateCustomerUserInfo(customerUserInfo);
            if(null!=customerUserInfo) {
                if (StringUtils.isNotEmpty(customerUserInfo.getStoreOpenCodeUrl()) && CustomerUserEnum.CUSTOMER_TYPE_1.getCode().intValue()==condition.getType().intValue()) {
                    path = customerUserInfo.getStoreOpenCodeUrl();
                } else if(StringUtils.isNotEmpty(customerUserInfo.getCustomerStoreCodeUrl()) && CustomerUserEnum.CUSTOMER_TYPE_0.getCode().intValue()==condition.getType().intValue()) {
                    path = customerUserInfo.getCustomerStoreCodeUrl();
                }
            }
            if(StringUtils.isEmpty(path)) {
                path =updateCustomerStoreUrl(customerUserInfo,condition.getType(),user);
            }
            if(CustomerUserEnum.CUSTOMER_TYPE_1.getCode().intValue()==condition.getType().intValue()){
                vo.setStoreOpenCodeUrl(path);
            }else{
                vo.setCustomerStoreCodeUrl(path);
            }
            result.setData(vo);
        } catch (Exception e) {
            logger.error("getCustomerAdminInfo查询当前会员管理平台信息失败：",e);
            result.setCode(BusinessCode.CODE_1001);
        }
        return result;
    }
    private String updateCustomerStoreUrl(CustomerUserInfo customerUserInfo,Integer type, CustomerUser user){
        MiniProgramStoreSharePicCondition conditionStore = new MiniProgramStoreSharePicCondition();
        CustomerUserInfo outletUser = customerLoginService.findCustomerUserByLevel();
        validateCustomerUserInfo(outletUser);
        ResponseResult<String> tokenResult = messageServiceClient.getAccessToken();
        if(CustomerConstant.DEFAULT_STATUS != tokenResult.getCode()){
            throw new BusinessException(BusinessCode.CODE_1001);
        }
        String token = tokenResult.getData();
        if (StringUtils.isEmpty(tokenResult.getData())) {
            throw new BusinessException(BusinessCode.CODE_1002);
        }
        if(CustomerUserEnum.CUSTOMER_TYPE_1.getCode().intValue()==type){
            conditionStore.setRow2(env.getProperty("store.one.title"));
            conditionStore.setRow3(env.getProperty("store.two.title"));
            conditionStore.setRow4(env.getProperty("store.three.title"));
        }else{
            conditionStore.setRow2(env.getProperty("user.one.title"));
            conditionStore.setRow3(env.getProperty("user.two.title"));
            conditionStore.setRow4(env.getProperty("user.three.title"));
        }
        conditionStore.setAccessToken(token);
        conditionStore.setNickName(customerUserInfo.getWechatName());
        conditionStore.setNickImg(customerUserInfo.getHeadImg());
        conditionStore.setOpenid(customerUserInfo.getOpenid());
        conditionStore.setPage(env.getProperty("store.page"));
        String scene = type.toString().concat("&").concat(user.getCustomerId().toString());
        if(outletUser.getId().equals(customerUserInfo.getParentId())){
            conditionStore.setScene(scene.concat("&").concat("1"));
        }else{
            conditionStore.setScene(scene.concat("&").concat("0"));
        }
        conditionStore.setBackground(env.getProperty("store.background"));
        logger.info("生成二维码参数：{}",JsonUtil.toJSONString(conditionStore));
        String path = graphicsGenerateService.generateMiniProgramStoreSharePic(conditionStore);
        CustomerUserInfo userInfo = new CustomerUserInfo();
        userInfo.setId(customerUserInfo.getId());
        if(CustomerUserEnum.CUSTOMER_TYPE_1.getCode().intValue()==type.intValue()){
            userInfo.setStoreOpenCodeUrl(path);
        }else{
            userInfo.setCustomerStoreCodeUrl(path);
        }
        userInfo.setUpdated(new Date());
        userInfo.setUpdatedByName(customerUserInfo.getWechatName());
        userInfo.setUpdatedBy(customerUserInfo.getId());
        customerLoginService.updateCustomerInfo(userInfo);
        return path;
    }
}
